package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneNotUniqueException;
import com.atguigu.gulimall.member.exception.UsernameNotUniqueException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.util.HttpUtils;
import com.atguigu.gulimall.member.vo.HttpResponseVo;
import com.atguigu.gulimall.member.vo.RegisterVo;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(RegisterVo registerVo) {
        MemberEntity memberEntity = new MemberEntity();

        //查询默认会员等级id
        MemberLevelEntity memberLevelEntity = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(memberLevelEntity.getId());
        //保存密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(registerVo.getPassword());
        memberEntity.setPassword(encode);
        //验证手机号是否唯一
        checkPhoneIsUnique(registerVo.getPhone());
        memberEntity.setMobile(registerVo.getPhone());
        //验证用户名是否唯一
        checkUsernameIsUnique(registerVo.getUserName());
        memberEntity.setUsername(registerVo.getUserName());
        memberEntity.setCreateTime(new Date());
        memberEntity.setNickname(registerVo.getUserName());
        //保存
        memberService.save(memberEntity);
    }

    @Override
    public void checkPhoneIsUnique(String phone) throws PhoneNotUniqueException {
        long count = memberService.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count>0){
            throw new PhoneNotUniqueException();
        }
    }

    @Override
    public void checkUsernameIsUnique(String username) throws UsernameNotUniqueException {
        long count = memberService.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new UsernameNotUniqueException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        String loginacct = userLoginVo.getLoginacct();
        String password = userLoginVo.getPassword();
        MemberEntity memberEntity = memberService.getOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if(memberEntity!=null){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, memberEntity.getPassword());
            if(matches){
                return memberEntity;
            }else {
                return null;
            }
        }else {
            return null;
        }
    }

    @Override
    public MemberEntity login(HttpResponseVo responseVo) {
        String uid = responseVo.getUid();
        MemberEntity memberEntity = memberService.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity!=null){
            //如果不是第一次登录
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(memberEntity.getAccessToken());
            entity.setExpiresIn(memberEntity.getExpiresIn());
            memberService.updateById(entity);

            memberEntity.setAccessToken(responseVo.getAccess_token());
            memberEntity.setExpiresIn(responseVo.getExpires_in());
            return memberEntity;
        }else {
            //如果是第一次登录
            memberEntity = new MemberEntity();
            memberEntity.setSocialUid(uid);
            memberEntity.setAccessToken(responseVo.getAccess_token());
            memberEntity.setExpiresIn(responseVo.getExpires_in());
            memberEntity.setCreateTime(new Date());
            try {
                //https://api.weibo.com/2/users/show.json
                Map<String,String> map = new HashMap<>();
                map.put("access_token",responseVo.getAccess_token());
                map.put("uid",uid);
                //获取个人用户信息
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);

                String toString = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(toString);
                memberEntity.setNickname(jsonObject.getString("name"));
                memberEntity.setGender(jsonObject.getString("gender").equals("m")?1:0);
                //....
            }catch (Exception e){

            }
            memberService.save(memberEntity);
            return memberEntity;
        }
    }

}